<template>
  <div class="table_config_form">
    <el-tabs tab-position="left" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="患者类型配置" name="patType">
        <div class="ky-mb10 flex flex-row justify-between align-center">
          <!-- <el-button size="small" @click="addEmergencyConfig" type="primary">新增</el-button> -->
          <!-- <div style="float:right">
            <el-button size="small" @click="resetPatTypeConfig()" type="primary">重置为初始数据</el-button>
          </div> -->
          <el-button size="small" @click="addPatTypeConfig" type="primary">新增</el-button>
          <!-- <div></div> -->
          <div class="red">{{tipSort}}</div>
          <el-button size="small" @click="resetPatTypeConfig()" type="primary">重置为初始数据</el-button>
        </div>
        <el-table
          :data="tabledataPatType"
          class="ky-table table_container dataPatTypeTable"
          style="width: 100%">
          <el-table-column label="序号" width="65" align="center">
            <template slot-scope="{ $index }">
              {{tabledataPatType[$index].sort}}
            </template>
          </el-table-column>
          <!-- <el-table-column
            prop="name"
            label="患者类型"
            min-width="200">
          </el-table-column> -->
          <el-table-column label="患者类型">
            <template slot-scope="{ $index }">
              <el-select size="mini" filterable placeholder="患者类型" @change="getTablePatType(tabledataPatType[$index].name, $index)" style="width: 45%;" v-model="tabledataPatType[$index].name">
                <el-option v-for="(item, index) in patTypeItemOptions" :key="index" :label="item.label" :value="item.label">
                  <span style="float: left">{{item.label}}</span>
                  <!-- <span style="float: right; color: #8492a6; font-size: 13px">{{item.label}}</span> -->
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="字体颜色">
            <template slot-scope="{ $index }">
              <div style="width: 30px;height: 30px;">
                <PublicInputColorPicker
                  :value="tabledataPatType[$index].fontColor"
                  :show-input="false"
                  placeholder="请选择颜色"
                  @change="(val)=>{tabledataPatType[$index].fontColor=val}"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="背景颜色">
            <template slot-scope="{ $index }">
              <div style="width: 30px;height: 30px;">
                <PublicInputColorPicker
                  :value="tabledataPatType[$index].bgColor"
                  :show-input="false"
                  placeholder="请选择颜色"
                  @change="(val)=>{tabledataPatType[$index].bgColor=val}"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="颜色是否启用">
            <template slot-scope="{ $index }">
              <el-switch
                size="small"
                v-model="tabledataPatType[$index].colorStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="" width="50">
            <template slot-scope="{ $index }">
              <el-button type="text" size="small" @click="delPatTypeConfig($index)">
                <i class="el-icon-delete fc_red"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="急诊标志配置" name="emergency">
        <div class="ky-mb10 flex flex-row justify-between align-center">
          <el-button size="small" @click="addEmergencyConfig" type="primary">新增</el-button>
          <div class="red">{{tipSort}}</div>
          <el-button size="small" @click="resetEmergencyConfig()" type="primary">重置为初始数据</el-button>
        </div>
        <el-table
          :data="tabledataEmergency"
          class="ky-table table_container emergencytTypeTable"
          style="width: 100%"
          height="570">
          <el-table-column label="序号" width="65" align="center">
            <template slot-scope="{ $index }">
              {{tabledataEmergency[$index].sort}}
            </template>
          </el-table-column>
          <el-table-column
            label="急诊标志"
            min-width="200">
            <template slot-scope="{ $index }">
              <el-input size="small" v-model="tabledataEmergency[$index].name"></el-input>
              <!-- <span v-show="(!!tabledataEmergency[$index].name) == true">{{tabledataEmergency[$index].name}}</span> -->
            </template>
          </el-table-column>
          <el-table-column label="值" width="70" align="center">
            <template slot-scope="{ $index }">
              <el-input size="small" v-model="tabledataEmergency[$index].value"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="字体颜色">
            <template slot-scope="{ $index }">
              <div style="width: 30px;height: 30px;">
                <PublicInputColorPicker
                  :value="tabledataEmergency[$index].fontColor"
                  :show-input="false"
                  placeholder="请选择颜色"
                  @change="(val)=>{tabledataEmergency[$index].fontColor=val}"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="背景颜色">
            <template slot-scope="{ $index }">
              <div style="width: 30px;height: 30px;">
                <PublicInputColorPicker
                  :value="tabledataEmergency[$index].bgColor"
                  :show-input="false"
                  placeholder="请选择颜色"
                  @change="(val)=>{tabledataEmergency[$index].bgColor=val}"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="颜色是否启用">
            <template slot-scope="{ $index }">
              <el-switch
                size="small"
                v-model="tabledataEmergency[$index].colorStatus"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="" width="50">
            <template slot-scope="{ $index }">
              <el-button type="text" size="small" @click="delEmergencyTableConfig($index)">
                <i class="el-icon-delete fc_red"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="列表数据配置" name="columnsconfig">
        <!-- <div class="ky-mb10 flex flex-row justify-between align-center">
          <el-button size="small" @click="addColumnsConfig" type="primary">新增</el-button>
          <div class="red">{{tipSort}}</div>
          <div></div>
        </div> -->
        <hisTableForm :from="'applyHis'" ref="hisTableForm" :dialog-visible-parent="dialogVisible"></hisTableForm>
        <!-- <el-table
          :data="tabledataColumnsconfig"
          class="ky-table table_container dataColumnsTable"
          style="width: 100%">
          <el-table-column label="序号" width="65" align="center">
            <template slot-scope="{ $index }">
              {{tabledataColumnsconfig[$index].sort}}
            </template>
          </el-table-column>
          <el-table-column label="名称">
            <template slot-scope="{ $index }">
              <el-input size="small" v-model="tabledataColumnsconfig[$index].label"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="字段">
            <template slot-scope="{ $index }">
              <el-select size="mini" clearable filterable allow-create placeholder="字段" style="width: 100%;" @change="tableDataChange($index)" v-model="tabledataColumnsconfig[$index].prop">
                <el-option v-for="(item, index) in tabledataColumnLabel" :key="index" :label="item.prop" :value="item.prop">
                  <span style="float: left">{{item.prop}}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{item.label}}</span>
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="宽度" width="150">
            <template slot-scope="{ $index }">
              <el-input size="small" v-model="tabledataColumnsconfig[$index].width"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="显示" width="150">
            <template slot-scope="{ $index }">
              <el-switch
                size="small"
                v-model="tabledataColumnsconfig[$index].show"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否">
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="" width="50">
            <template slot-scope="{ $index }">
              <el-button type="text" size="small" @click="delColumnusConfig($index)">
                <i class="el-icon-delete fc_red"></i>
              </el-button>
            </template>
          </el-table-column>
        </el-table> -->
      </el-tab-pane>
      <!-- <el-tab-pane label="列表数据拆成组件" name="hisTableConfig">
        <hisTableForm></hisTableForm>
      </el-tab-pane> -->
    </el-tabs>
  </div>
</template>

<script>
import Sortable from 'sortablejs'
import { Options } from '@/utils/constant'
import { getEmergencyValueByName } from '@/utils/utils'
import hisTableForm from './hisTableForm'
import PublicInputColorPicker from '@/components/color-picker/index'
export default {
  components: {
    PublicInputColorPicker,
    hisTableForm
  },
  data() {
    return {
      tipSort: '拖动列表可进行排序',
      tabledataEmergency: [],
      tabledataPatType: JSON.parse(JSON.stringify(Options.patientTypeItemOptions)),
      tabledataColumnsconfig: [],
      tabledataColumnLabel: JSON.parse(JSON.stringify(Options.checkTableColumnsConfig)).sort((a, b) => a.prop.localeCompare(b.prop)),
      emergencyOptionsOptions: Options.emergencyOptions,
      emergencyOptionsMapper: {},
      patTypeItemOptions: Options.patientTypeItemOptions,
      patTypeItemOptionsMapper: {},
      activeName: 'patType',
      alreadyHavePatType: false,
      dialogVisible: false
    }
  },
  created() {
    // this.setData()
    this.setEmergencyTable(this.emergencyOptionsOptions)
  },
  methods: {
    resetPatTypeConfig() {
      this.setPatTypeTable(Options.patientTypeItemOptions)
      console.log('this.tabledataPatType', this.tabledataPatType)
    },
    getTablePatType(val, index) {
      if (this.tabledataPatType.filter(item => item.name === val).length > 1 || val === '') {
        this.$parent.$parent.$parent.$parent.alreadyHavePatType(true)
      } else {
        Options.patientTypeItemOptions.forEach(element => {
          if (element.label === val) {
            this.tabledataPatType[index].name = element.label
            this.tabledataPatType[index].value = element.value
            // this.tabledataPatType[index].sort = element.sort
          }
        })
        this.$parent.$parent.$parent.$parent.alreadyHavePatType(false)
      }
      // console.error('this.tabledataPatType', this.tabledataPatType)
    },
    addPatTypeConfig() {
      if (this.tabledataPatType.length != Options.patientTypeItemOptions.length) {
        const _columns = JSON.parse(JSON.stringify(this.tabledataPatType))
        _columns.unshift({ bgColor: '', colorStatus: false, fontColor: '', name: '', value: 0, sort: 0 })
        this.tabledataPatType = _columns
      } else {
        this.$message.warning('已经具备所有的患者类型无需再添加')
      }
    },
    delPatTypeConfig(idx) {
      let chooseTablePatType = Options.patientTypeItemOptions.filter(item => item.label === this.tabledataPatType[idx].name)
      this.tabledataPatType.splice(idx, 1)
      this.tabledataPatType.forEach((item, index) => {
        item.sort = index + 1
        if (item.name === chooseTablePatType[0].label) {
          item.value = chooseTablePatType[0].value
        }
      })
      if (this.tabledataPatType.filter(item => item.name === this.tabledataPatType[idx].name).length > 1) {
        this.$parent.$parent.$parent.$parent.alreadyHavePatType(true)
      } else {
        this.$parent.$parent.$parent.$parent.alreadyHavePatType(false)
      }
    },
    delEmergencyTableConfig(idx) {
      console.log('delEmergencyTableConfig')
      this.tabledataEmergency.splice(idx, 1)
      this.tabledataEmergency.forEach((item, index) => {
        item.sort = index + 1
      })
    },
    addEmergencyConfig() {
      const tabledataEmergency = JSON.parse(JSON.stringify(this.tabledataEmergency))
      let value = 0
      let sort = 0
      tabledataEmergency.forEach(item => {
        if (item.value >= value) {
          value = item.value + 1
          sort = item.sort + 1
        }
      })
      // tipsSwitch 鼠标移上去显示的toolTips
      let item = { value, name: '', bgColor: '', fontColor: '', colorStatus: false, sort }
      tabledataEmergency.unshift(item)
      this.tabledataEmergency = tabledataEmergency
    },
    resetEmergencyConfig() {
      this.setEmergencyTable(Options.emergencyOptions)
      console.log('this.tabledataEmergency', this.tabledataEmergency)
    },
    handleClick(val) {
      if (val.label === '列表数据配置') {
        this.dialogVisible = true
      }
      // ...
    },
    // 获取设置数据
    getData() {
      const params = {
        checkHisTable: this.tabledataEmergency,
        checkPatTypeTable: this.tabledataPatType,
        columnsConfig: this.$refs.hisTableForm.tableDataColumnsConfig.filter(cc => cc.label && cc.prop)
      }
      return JSON.parse(JSON.stringify(params))
    },
    setData(data) {
      console.log('tableConfig setData ====', data)
      this.setEmergencyTable(data ? data.checkHisTable : this.emergencyOptionsOptions)
      this.setPatTypeTable(data ? data.checkPatTypeTable : this.patTypeItemOptions)
      this.$refs.hisTableForm.setColumnsTable(data ? data.columnsConfig.sort((a, b) => a.sort - b.sort) : this.tabledataColumnLabel)
      this.$nextTick(() => {
        const el = document.querySelector('.dataPatTypeTable .el-table__body-wrapper tbody')
        Sortable.create(el, {
          sort: true,
          fallbackClass: 'cursor-pointer',
          ghostClass: 'sortable-drag',
          chosenClass: 'sortable-drag',
          dragClass: 'sortable-drag',
          scroll: true,
          onEnd: (event) => {
            const { oldIndex, newIndex } = event
            this.updateRowOrder(oldIndex, newIndex, 'tabledataPatType')
          }
        })
        Sortable.create(document.querySelector('.emergencytTypeTable .el-table__body-wrapper tbody'), {
          sort: true,
          ghostClass: 'sortable-drag',
          chosenClass: 'sortable-drag',
          dragClass: 'sortable-drag',
          fallbackClass: 'cursor-pointer',
          scroll: true,
          onEnd: (event) => {
            const { oldIndex, newIndex } = event
            this.updateRowOrder(oldIndex, newIndex, 'tabledataEmergency')
          }
        })
        // Sortable.create(document.querySelector('.dataColumnsTable .el-table__body-wrapper tbody'), {
        //   sort: true,
        //   ghostClass: 'sortable-drag',
        //   chosenClass: 'sortable-drag',
        //   dragClass: 'sortable-drag',
        //   fallbackClass: 'cursor-pointer',
        //   scroll: true,
        //   onEnd: (event) => {
        //     const { oldIndex, newIndex } = event
        //     this.updateRowOrder(oldIndex, newIndex, 'tabledataColumnsconfig')
        //   }
        // })
      })
    },
    updateRowOrder(oldIndex, newIndex, tableDataName) {
      const movedItem = this[tableDataName].splice(oldIndex, 1)[0]
      this[tableDataName].splice(newIndex, 0, movedItem)
      const _columns = JSON.parse(JSON.stringify(this[tableDataName]))
      _columns.forEach((item, index) => {
        item.sort = index + 1
      })
      if (tableDataName == 'tabledataColumnsconfig') {
        let scrollTop = 0
        let $tbody = document.querySelector('.dataColumnsTable .el-table__body-wrapper')
        scrollTop = $tbody.scrollTop
        this[tableDataName] = []
        this.$nextTick(() => {
          this[tableDataName] = _columns
          this.$nextTick(() => {
            $tbody.scrollTop = scrollTop
          })
        })
      } else {
        this[tableDataName] = []
        this.$nextTick(() => {
          this[tableDataName] = _columns
        })
      }
    },
    // 设置急诊标志配置
    setEmergencyTable(checkHisTable) {
      let _d = []
      checkHisTable.forEach((item, index) => {
        let obj = {
          value: item.value ? item.value : getEmergencyValueByName(item.name || item.label),
          name: item.name || item.label,
          bgColor: item.bgColor ? item.bgColor : '',
          fontColor: item.fontColor ? item.fontColor : '',
          colorStatus: item.colorStatus ? item.colorStatus : false,
          sort: index + 1
        }
        _d.push(obj)
      })
      this.tabledataEmergency = _d
    },
    // 患者类型配置
    setPatTypeTable(checkPatTypeTable) {
      let _d = []
      checkPatTypeTable.forEach((item, index) => {
        let obj = {
          value: item.value,
          name: item.name || item.label,
          bgColor: item.bgColor ? item.bgColor : '',
          fontColor: item.fontColor ? item.fontColor : '',
          colorStatus: item.colorStatus ? item.colorStatus : false,
          sort: index + 1
        }
        _d.push(obj)
      })
      this.tabledataPatType = _d
    }
    // delColumnusConfig(idx) {
    //   this.tabledataColumnsconfig.splice(idx, 1)
    //   this.tabledataColumnsconfig.forEach((item, index) => {
    //     item.sort = index + 1
    //   })
    // },
    // addColumnsConfig() {
    //   const _columns = JSON.parse(JSON.stringify(this.tabledataColumnsconfig))
    //   _columns.unshift({ label: '', width: '100', prop: '', show: true, sort: 0 })
    //   this.tabledataColumnsconfig = _columns
    // },
    // tableDataChange(index) {
    //   const selectedLabel = this.tabledataColumnsconfig[index].prop
    //   this.tabledataColumnLabel.forEach((item, i) => {
    //     if (item.prop === selectedLabel) {
    //       this.tabledataColumnsconfig[index].label = item.label
    //       this.tabledataColumnsconfig[index].show = item.show
    //       this.tabledataColumnsconfig[index].sort = item.sort
    //       this.tabledataColumnsconfig[index].width = item.width
    //     }
    //   })
    // }
  }
}
</script>

<style lang="scss" scoped>
  /deep/ .el-form-item__label{
    padding: 0;
  }
  /deep/ .el-input-number .el-input__inner{
    text-align: left;
  }
  /deep/ .el-table td{
    padding: 4px 0;
  }
  .table_container /deep/ .el-table__body-wrapper{
    max-height: calc(100vh - 380px);
    overflow-y: auto;
  }
  /deep/ .sortable-drag {
    background: #C7F2F9;
  }
</style>
